Imports System.Windows.Forms
Imports atcMwGisUtility

Public Class frmConsolidate

    Private _dtResults As DataTable
    Private _WRDBShapeFile As MapWinGIS.Shapefile
    Private GISMap As MapWindow.Interfaces.IMapWin

    <CLSCompliant(False)> _
    Public Sub New(ByVal dtResults As DataTable)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _dtResults = dtResults
        _WRDBShapeFile = MainWRDB.MapWin.Layers(GisUtil.LayerIndex(MainWRDB.WRDBLayerName)).GetObject
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub frmConsolidate_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cboLayers.Items.Clear()
        GISMap = MainWRDB.MapWin
        With GISMap
            Application.UseWaitCursor = True
            .StatusBar.ShowProgressBar = True
            For i As Integer = 0 To .Layers.NumLayers - 1
                If .Layers(i) IsNot Nothing Then
                    With .Layers(i)
                        If .LayerType = MapWindow.Interfaces.eLayerType.PolygonShapefile Then
                            cboLayers.Items.Add(.Name)
                        End If
                    End With
                End If
                .StatusBar.ProgressBarValue = i * 100.0 / .Layers.NumLayers
                Application.DoEvents()
            Next
            .StatusBar.ShowProgressBar = False
            Application.UseWaitCursor = False
        End With
        With cboStats
            .Items.Clear()
            .Items.AddRange(New String() {"Number of Observations", "Minimum Value", "Maximum Value", "Average Value", "Number of Excursions Outside Min/Max Criteria", "Percent of Excursions Outside Min/Max Criteria"})
            .SelectedIndex = 0
        End With
    End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        With New SaveFileDialog
            .AddExtension = True
            .CheckPathExists = True
            .DefaultExt = ".shp"
            .FileName = txtNewShapefile.Text
            .Filter = "Shape Files (*.shp)|*.shp"
            .InitialDirectory = MainWRDB.WRDBShapeDirectory
            .OverwritePrompt = True
            .SupportMultiDottedExtensions = False
            If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                txtNewShapefile.Text = .FileName
            End If
        End With
    End Sub

    Private Sub cboLayers_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboLayers.SelectionChangeCommitted, cboStats.SelectionChangeCommitted
        txtNewShapefile.Text = cboStats.Text & " in " & cboLayers.Text & ".shp"
    End Sub

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Me.Hide()

        If txtNewShapefile.Text = "" Then
            MessageBox.Show("You must enter or select the name for the new shape file to be created.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Exit Sub
        End If
        Dim NewLayerName As String = txtNewShapefile.Text.Replace(".shp", "").Replace("/", "-")
        Dim lyrPoly As MapWindow.Interfaces.Layer = Nothing
        With GISMap
            For i As Integer = 0 To .Layers.NumLayers - 1
                If .Layers(i) IsNot Nothing Then
                    If .Layers(i).Name = cboLayers.Text Then lyrPoly = .Layers(i)
                    If .Layers(i).FileName = txtNewShapefile.Text Or .Layers(i).Name = NewLayerName Then .Layers.Remove(i)
                End If
            Next
            If lyrPoly Is Nothing Then Exit Sub
        End With

        Application.UseWaitCursor = True

        Dim sfNew As New MapWinGIS.Shapefile
        With sfNew
            .Close()
            Dim FileName As String = txtNewShapefile.Text
            If Not FileName.Contains("\") Then FileName = MainWRDB.WRDBShapeDirectory & "\" & FileName
            Dim res As Boolean
            res = MapWinGeoProc.DataManagement.DeleteShapefile(FileName)
            res = MapWinGeoProc.DataManagement.CopyShapefile(lyrPoly.FileName, FileName)

            If .Open(FileName) Then
                .StartEditingShapes(True)
                .StartEditingTable()

                'add new fields for statistics

                For i As Integer = 0 To 3
                    Dim fld As MapWinGIS.Field = New MapWinGIS.Field
                    fld.Name = Choose(i + 1, "NumResult", "MinResult", "MaxResult", "AvgResult")
                    Select Case i
                        Case 0 : fld.Type = MapWinGIS.FieldType.INTEGER_FIELD
                        Case Else
                            fld.Type = MapWinGIS.FieldType.DOUBLE_FIELD
                            fld.Precision = 5
                    End Select
                    .EditInsertField(fld, .NumFields)
                Next

                GISMap.StatusBar.ShowProgressBar = True
                GISMap.StatusBar.Item(2).Text = "Creating WRDB consolidation shape file..."

                For index As Integer = 0 To .NumShapes - 1
                    Dim shp As MapWinGIS.Shape = .Shape(index)
                    'add computed fields
                    Dim Stats() As Object = GetWRDBStats(shp)
                    For j As Integer = 0 To 3
                        If Not .EditCellValue(.NumFields - 4 + j, index, Stats(j)) Then Exit Sub
                    Next j
                    GISMap.StatusBar.ProgressBarValue = CInt(index * 100.0 / (.NumShapes - 1))
                    Application.DoEvents()
                Next

                GISMap.StatusBar.ShowProgressBar = False
                GISMap.StatusBar.Item(2).Text = "Saving to " & FileName
                .StopEditingTable()
                .StopEditingShapes(True, True)
            End If

            'create a coloring scheme

            GISMap.StatusBar.Item(2).Text = "Creating color scheme..."
            Dim colorScheme As New MapWinGIS.ShapefileColorScheme
            colorScheme.FieldIndex = .NumFields - 4 + cboStats.SelectedIndex
            'find range of values
            Dim minvalue As Double = Double.MaxValue
            Dim maxvalue As Double = Double.MinValue
            For i As Integer = 0 To .NumShapes - 1
                Dim value As Object = sfNew.CellValue(colorScheme.FieldIndex, i)
                If Not IsDBNull(value) Then
                    minvalue = Math.Min(minvalue, value)
                    maxvalue = Math.Max(maxvalue, value)
                End If
            Next

            If minvalue <> Double.MaxValue Then
                'If minvalue <> maxvalue And minvalue <> Double.MaxValue Then
                Dim colorBreak As MapWinGIS.ShapefileColorBreak
                colorBreak = New MapWinGIS.ShapefileColorBreak
                With colorBreak
                    .Caption = "None"
                    .StartValue = DBNull.Value
                    .EndValue = DBNull.Value
                    .StartColor = System.Convert.ToUInt32(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gainsboro))
                    .EndColor = System.Convert.ToUInt32(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Gainsboro))
                End With
                colorScheme.Add(colorBreak)

                For i As Integer = 0 To 3
                    colorBreak = New MapWinGIS.ShapefileColorBreak
                    With colorBreak
                        Dim mn As Double = minvalue + (maxvalue - minvalue) * i / 4
                        Dim mx As Double = minvalue + (maxvalue - minvalue) * (i + 1) / 4
                        .Caption = String.Format("{0:0.00}-{1:0.00}", mn, mx)
                        .StartValue = mn
                        .EndValue = mx
                        .StartColor = System.Convert.ToUInt32(System.Drawing.ColorTranslator.ToOle(Choose(i + 1, Drawing.Color.Blue, Drawing.Color.Green, Drawing.Color.Yellow, Drawing.Color.Red, Drawing.Color.LightPink)))
                        .EndColor = System.Convert.ToUInt32(System.Drawing.ColorTranslator.ToOle(Choose(i + 2, Drawing.Color.Blue, Drawing.Color.Green, Drawing.Color.Yellow, Drawing.Color.Red, Drawing.Color.LightPink)))
                    End With
                    colorScheme.Add(colorBreak)
                Next
            End If

            .Close()

            'shape file is created, now add to view

            GISMap.StatusBar.Item(2).Text = "Adding layer..."

            With MainWRDB.MapWin.Layers.Add(FileName, NewLayerName)
                .LineOrPointSize = 1
                .OutlineColor = Color.Gainsboro
                .Color = Drawing.Color.Gainsboro
                .UseTransparentColor = False
                MainWRDB.MapWin.Layers.MoveLayer(.Handle, 1, GisUtil.GroupHandle(MainWRDB.WRDBGroupName))
                If colorScheme.NumBreaks > 0 Then .ColoringScheme = colorScheme
                .Visible = True
            End With
        End With

        GISMap.StatusBar.Item(2).Text = ""
        Application.UseWaitCursor = False

        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    ''' <summary>
    ''' Find all WRDB stations within this polygon and compute statistics
    ''' </summary>
    Private Function GetWRDBStats(ByRef shp As MapWinGIS.Shape) As Object
        'Dim Value(3) As Object
        'For StatIndex As Integer = 0 To 3
        '    Value(StatIndex) = Choose(StatIndex + 1, 0, Double.MaxValue, Double.MinValue, 0)
        'Next
        'Dim Count As Integer = 0
        'Dim utils As New MapWinGIS.Utils
        'For i As Integer = 0 To _WRDBShapeFile.NumShapes - 1
        '    Dim pt As MapWinGIS.Point = _WRDBShapeFile.QuickPoint(i, 0)
        '    If utils.PointInPolygon(shp, pt) Then
        '        'find correct record in result table
        '        Dim StationID As String = _WRDBShapeFile.CellValue(0, i)
        '        Dim PCode As String = StringSplit(CType(MainForm, frmMainMW).cboPCode.Text, " - ")(0)
        '        _dtResults.DefaultView.RowFilter = String.Format("Station_ID='{0}' AND PCode='{1}'", StationID, PCode)
        '        If _dtResults.DefaultView.Count = 1 Then
        '            Dim row As DataRowView = _dtResults.DefaultView.Item(0) 'should be only one matching record
        '            For StatIndex As Integer = 0 To 3
        '                Select Case StatIndex
        '                    Case 0 : Value(StatIndex) += row.Item("NumResult")
        '                    Case 1 : Value(StatIndex) = Math.Min(Value(StatIndex), row.Item("MinResult"))
        '                    Case 2 : Value(StatIndex) = Math.Max(Value(StatIndex), row.Item("MaxResult"))
        '                    Case 3 : Value(StatIndex) += row.Item("AvgResult") * row.Item("NumResult")
        '                End Select
        '            Next
        '            Count += row.Item("NumResult")
        '        End If
        '    End If
        'Next
        'For StatIndex As Integer = 0 To 3
        '    If Count = 0 Then
        '        Value(StatIndex) = DBNull.Value
        '    Else
        '        Select Case StatIndex
        '            Case 3 : Value(StatIndex) /= Count
        '        End Select
        '    End If
        'Next
        'Return Value
    End Function
End Class
